﻿using System;
using System.Windows.Forms;
using Business.Forms;

namespace Business.Controls
{
    public class CommandSave : CommandBase
    {
        public CommandSave()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // CommandInsert
            // 
            this.Text = "Inserir";
            Atalho = Keys.F7;
            this.Click += new System.EventHandler(this.CommandInsert_Click);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CommandInsert_KeyDown);
            this.ResumeLayout(false);

        }

        private void CommandInsert_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyData == Atalho)
            {
                Save();
            }
        }

        private void Save()
        {
            BeforeOperation();
            try
            {
                if (Form == null)
                {
                    return;
                }
                var valid = Form.Validate();
                if (valid.HasError)
                {
                    throw new Exception(valid.MensagemErro());
                }
                Form.Save();
                Form.Form.DialogResult = DialogResult.OK;
                Form.Form.Close();
            }
            catch (Exception ex)
            {
                ExibeErro("Erro ao salvar dados.\n" + ex.Message);
            }
            AfterOperation();
        }

        private void CommandInsert_Click(object sender, System.EventArgs e)
        {
            Save();
            
        }

        public override void Actived()
        {
            if (Form == null)
            {
                return;
            }
            var perm = Seguranca.SegurancaUtils.GetPermissaoForm(Form.Form.Name);
            if (Form.FormState == FormState.Inserting)
            {
                if (Form != null && Form.Permissao != null && perm.PermissaoInsert)
                {
                    Enabled = true;
                }
                else
                {
                    Enabled = false;
                }
            }
            if (Form.FormState == FormState.Updating)
            {
                if (Form != null && Form.Permissao != null && perm.PermissaoUpdate)
                {
                    Enabled = true;
                }
                else
                {
                    Enabled = false;
                }
            }
        }
    }
}
